/* ====================================================================
 * (#)Header: DomTransformer.java
 * (#)Revision: 
 * (#)Date Created: Mar 2, 2007 12:07:22 AM
 * (#)Created By: Karol Wozniak
 * ====================================================================
 *
 * Copyright (c) 2007 karolak .  All rights reserved.
 *
 * ====================================================================
 * 
 * The software application represented here is the sole property of 
 * karolak. Its unauthorized utilization is expressly prohibited.
 * 
 * ====================================================================
 */
package com.karolak.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

/**
 * <code>DomTransformer</code> is used to ....
 * 
 * @author <a href="mailto:kwozniak@hotmail.com">Karol Wozniak</a>
 */
public class DomTransformer {

	static {
		instance = new DomTransformer();
	}
	private static DomTransformer instance;

	private DomTransformer() {
	}

	public Document transform(String xml, boolean namespaceAware) {
		Document document = null;
		if (xml == null) {
			return document;
		}
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		domFactory.setNamespaceAware(namespaceAware);
		DocumentBuilder builder = null;
		try {
			builder = domFactory.newDocumentBuilder();
			document = builder.parse(new ByteArrayInputStream(xml.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return document;
	}

	public String transform(Document document) {
		String xml = null;
		if (document == null) {
			return xml;
		}
		StringWriter writer = new StringWriter();
		try {
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			Result result = new StreamResult(writer);
			Source source = new DOMSource(document);
			transformer.transform(source, result);
			xml = writer.toString();
		} catch (TransformerException e) {
			new RuntimeException(e);
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
			}
		}
		return xml;
	}

	// === get/set === //
	public static DomTransformer getInstance() {
		return instance;
	}
}
